package main

import (
	"fmt"
	"time"

	"github.com/gin-gonic/gin"
)

//自定义中间件
func IPAuthMiddleWare() gin.HandlerFunc {
	return func(c *gin.Context) {
		ipList := []string{
			"127.0.0.1",
		}
		flag := false
		clientIP := c.ClientIP() //获取客户端ip
		for _, ip := range ipList {
			if clientIP == ip { //判断客户端ip是否有有效权限
				flag = true
				break
			}
		}
		if !flag {
			c.String(401, "%s 权限不足，无法操作", clientIP)
			c.Abort() //挂起其他相应函数
		}
	}
}

func main() {
	r := gin.Default()
	//自定义一个IPAuthMiddleWare()中间件并且使用
	r.Use(IPAuthMiddleWare(), gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string {
		// 你的自定义格式// LoggerWithFormatter 中间件会将日志写入 gin.DefaultWriter
		return fmt.Sprintf("%s - [%s] \"%s %s %s %d %s \"%s\" %s\"\n",
			param.ClientIP,
			param.TimeStamp.Format(time.RFC1123),
			param.Method,
			param.Path,
			param.Request.Proto,
			param.StatusCode,
			param.Latency,
			param.Request.UserAgent(),
			param.ErrorMessage,
		)
	}))
	r.GET("/test", func(c *gin.Context) {
		c.String(200, "hello world~")
	})
	r.Run(":8081")
}
